const { baseUrl, CODE } = require('../../config/api.js')
const app = getApp()
Page({
  data: {
    list: [],
    pageNo : 1, // 数据多可以做出上拉刷新
    pageSize : 5,
    count: 0
  },
  onLoad() {
    this.getList()
  },
  // 请求帖子列表
  getList(flag) {
    wx.request({
      url: baseUrl + '/api/postInfos',
      method: 'GET',
      data: {
        pageNo: this.data.pageNo,
        pageSize: this.data.pageSize,
        status: 1
      },
      success: (res) => {
        res = res.data
        if (res.code === CODE) {
          if (flag) {
            // console.log('true ' + this.data.pageNo)
            let arr = this.data.list
            arr = arr.concat(res.data.list)
            // console.log(arr.length)
            this.setData({
              list: arr || []
            })
          } else {
            // console.log('false ' + this.data.pageNo)
            this.setData({
              list: res.data.list,
              count: res.data.count
            })
          }
          // 停止刷新
          wx.stopPullDownRefresh()
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  // 跳转新增帖子页面
  addContent() {
    wx.navigateTo({
      url: '/pages/add/add?category=1'
    })
  },
  // 删除帖子
  onDelete(options) {
    const id = options.detail.id
    wx.showModal({
      content: '确认删除该分享么',
      success: (res) => {
        if (res.confirm) {
          const arr = this.data.list.filter((element, index) => {
            return this.data.list[index].postInfo.id != id
          })
          this.setData({
            list: arr
          })
          // 请求从后台删除
          wx.request({
            url: baseUrl + '/api/postInfo?id=' + id,
            method: 'DELETE'
          })
        }
      }
    })
  },
  // 评论帖子
  onRemark(options) {
    // options 接受到postId, parentId, toUserId
    // 通知组件remark显示,并且传入postId, parentId,t oUserId
    this.component = this.selectComponent('#remark')
    this.component.show(options.detail)
  },
  // 评论帖子成功得回调
  onSuccess(params) {
    // console.log(params)
    this.components = this.selectAllComponents('.conponents')
    const block = this.components.find((item, idx) => {
      return item.id == params.detail.postId
    })
    block.onSuccess(params.detail)
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      pageNo: 1
    }, () => {
      this.getList()
    })
  },
  // 上拉加载
  onReachBottom() {
    if (this.data.list.length >= this.data.count) {
      return
    }
    this.setData({
      pageNo: this.data.pageNo + 1
    }, () => {
      this.getList(true)
    })
  },
  // 分享
  onShareAppMessage() {
    return {
      title: '实习资源分享',
      path: '/pages/rent/rent'
    }
  }
}) 